package cn.iocoder.ny.module.mall.controller.admin.system;



import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthPermissionInfoRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.SystemUserVo;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.system.SystemUsers;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.system.SystemUsersMapper;
import cn.iocoder.yudao.module.system.service.permission.MenuService;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.system.ISystemUserService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wechat.pay.java.service.weixinpayscanandride.model.UserServiceEntity;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * @author luchunhong
 * @date 2024/10/22/ 17:37
 * @description:
 */

@RestController
@RequestMapping("system")
public class SystemUserController {
    @Resource
    private SystemUsersMapper systemUsersMapper;
    @Resource
    private ISystemUserService systemUserService;
    @Resource
    private AdminUserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private MenuService menuService;

    /**
     * 当登录时先获取到用户所输入的账号 以此来查询该用户所拥有的tenantId
     * @param
     * @return
     */
    @PostMapping("/get-id-by-username")
    @PermitAll
    public CommonResult<Map<String, Object>> getTenantIdByUserName(@RequestBody SystemUsers systemUsers) {
        // 通过用户名和密码查询匹配的用户
        Map<String, Object> systemHash = null;
        try {
            systemHash = systemUserService.getTenantIdByUserName(systemUsers);
            return success(systemHash);

        } catch (RuntimeException e) {
            return error(500,e.getMessage());
        }
    }
    @GetMapping("/get-permission-info-saas")
    @Operation(summary = "saas商城获取用户信息")
    @PermitAll
    public CommonResult<AuthPermissionInfoRespVO> getPermissionInfo() {
        // 1.1 获得用户信息
        if (ObjectUtils.isEmpty(getLoginUser())){
            return error(509,null);
        }
        AdminUserDO user = userService.getUser(getLoginUserId());
        if (user == null) {
            return error(509, null);
        }
        // 1.2 获得角色列表
        Set<Long> roleIds = permissionService.getUserRoleIdListByUserId(getLoginUserId());
        if (CollUtil.isEmpty(roleIds)) {
            return success(AuthConvert.INSTANCE.convert(user, Collections.emptyList(), Collections.emptyList()));
        }
        List<RoleDO> roles = roleService.getRoleList(roleIds);
        roles.removeIf(role -> !CommonStatusEnum.ENABLE.getStatus().equals(role.getStatus())); // 移除禁用的角色

        // 1.3 获得菜单列表
        Set<Long> menuIds = permissionService.getRoleMenuListByRoleId(convertSet(roles, RoleDO::getId));
        List<MenuDO> menuList = menuService.getMenuList(menuIds);
        menuList = menuService.filterDisableMenus(menuList);

        // 2. 拼接结果返回
        return success(AuthConvert.INSTANCE.convert(user, roles, menuList));
    }



    /**
     * 通过tenantId查询所有用户
     */
    @PostMapping("getAllUserList")
    public CommonResult<List<SystemUserVo>> getAllUser(@RequestBody SystemUsers systemUsers) {
        List<SystemUserVo> userListByTenantId = systemUserService.getUserListByTenantId(systemUsers.getTenantId(), null);
        return CommonResult.success(userListByTenantId);
    }

   // 判断该用户是否设置密码
    @PostMapping("hasSetPassoword")
    public CommonResult<String> hasSetPassoword() {
        Boolean hasSetPassoword = null;
        try {
            hasSetPassoword = systemUserService.hasSetPassoword();
        } catch (RuntimeException e) {
            return error(508,e.getMessage());
        }
        if (hasSetPassoword){
            return success("ok");
        }
        return null;
    }

    @PostMapping("bindPassword")
    public CommonResult bindPassword(@RequestBody Map<String,String> map) {
        try {
            Boolean b = systemUserService.bindPassword(map);
            if (b){
                return success("绑定成功");
            }
        } catch (RuntimeException e) {
            return error(500,e.getMessage());
        }
        return null;
    }

    /**
     * 通过UserId查询用户信息
     */
    @PostMapping("getUserByUserId")
    public CommonResult<Map<Object,Object>> getUserByUserId(@RequestBody HashMap<String,Object> map) {
        Object userId = map.get("userId");
        SystemUsers userInfo = systemUserService.lambdaQuery().eq(SystemUsers::getId, userId).eq(SystemUsers::getStatus, 0)
                .eq(SystemUsers::getDeleted, 0).one();
        Map<Object, Object> userInfoMap = new HashMap<>();
        userInfoMap.put("userId",userInfo.getId());
        userInfoMap.put("email",userInfo.getEmail());
        userInfoMap.put("mobile",userInfo.getMobile());
        userInfoMap.put("nickname",userInfo.getNickname());
        return success(userInfoMap);
    }

}
